﻿using System;
using System.Collections.Generic;
using System.Net.Mail;
using NHibernate;
using Web.Model;

namespace Web.HelperClasses
{
    public class NotificationSender
    {
        readonly string fromAddress;
    	readonly SmtpClient client;
        readonly ISession session;

        public NotificationSender(string from, ISession session)
        {
            fromAddress = from;
            client = new SmtpClient();
            this.session = session;
        }


        public void SendAll()
        {
            IList<Notification> notifications = session.CreateCriteria<Notification>().List<Notification>();
            foreach (Notification note in notifications)
            {
                MailMessage message = new MailMessage();
                message.From = new MailAddress(fromAddress);
                message.To.Add(new MailAddress(note.Email));
                message.Subject = note.Subject;
                message.Body = note.Body;
                message.IsBodyHtml = true;

                client.Send(message);

                SentNotification sent = new SentNotification()
                {
                    Email = note.Email,
                    Subject = note.Subject,
                    Body = note.Body,
                    Date = DateTime.Now
                };

                session.Save(sent);
                session.Delete(note);
                
            }
        }
    }
}